import datetime

from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QWidget, QListWidgetItem, QCheckBox, QHBoxLayout, QLabel, \
    QLineEdit, QSizePolicy

from app.view.TodoList import Ui_TodoListForm


class TodoTask:
    """任务数据模型"""

    def __init__(self, title, completed=False, created_at=None):
        self.title = title
        self.completed = completed
        self.created_at = created_at or datetime.datetime.now()


class TodoListWidget(QWidget):
    """待办事项列表页面"""

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setObjectName("TodoListWidget")
        self.ui = Ui_TodoListForm()
        self.ui.setupUi(self)
        self.setStyleSheet("""
            QWidget#TodoListWidget {
                background-repeat: no-repeat;
                background-position: center;
                background-size: cover;
                font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
            }
            QListWidget {
                background: transparent;
                border: none;
                padding: 5px;
            }
            QLabel {
                background: transparent;
            }
            QPushButton {
                background-color: rgba(52, 152, 219, 0.8);
                border-radius: 20px;
                padding: 8px 16px;
                color: white;
                font-weight: 500;
                border: none;
                transition: background-color 0.3s, transform 0.2s;
            }
            QPushButton:hover {
                background-color: rgba(41, 128, 185, 0.9);
                transform: translateY(-2px);
            }
            QPushButton:pressed {
                transform: translateY(0);
            }
            #dayLabel {
                font-size: 18px;
                font-weight: 600;
                color: #ffffff;
                text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
            }
        """);

        # 初始化数据
        self.tasks = []
        # 每个元组包含建议标题和完成状态
        self.suggestions = [
            ("B2B在线系统原型图测试", False),
            ("B2B在线系统业务流程图绘制", True),  # 已完成
            ("分销商城开发框架调节", False),
            ("官网资讯中心开发排期", True),  # 已完成
            ("房贷服务费计算规则-统一按应收利息计算", False),
            ("房贷幸福还款日统一还款日", False),
            ("陆鹰自由商城系统与店铺通对接", False)
        ]

        # 设置当前日期
        self.update_date()

        # 添加任务输入框
        self.task_input = QLineEdit(self.ui.taskListWidget)
        self.task_input.setPlaceholderText("请输入任务内容，按回车键添加")
        self.task_input.setStyleSheet("""
            QLineEdit {
                background-color: rgba(0, 0, 0, 0.8); /* 黑色背景 */
                border: 1px solid rgba(52, 152, 219, 1); /* 更明显的边框 */
                border-radius: 10px;
                padding: 6px 24px;
                font-size: 14px;
                color: #ffffff; /* 白色文本 */
                min-width: 150px;
                max-width: 380px;
                min-height: 30px;
                z-index: 100;
            }
            QLineEdit:focus {
                outline: none;
                background-color: rgba(0, 0, 0, 0.8); /* 80%透明黑色背景 */
                border: 1px solid rgba(52, 152, 219, 0.8); /* 更明显的边框 */
                box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.5);
            }
        """)
        # 直接替换按钮
        self.ui.verticalLayout.addWidget(self.task_input)
        # 调整大小策略
        self.task_input.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        # 确保可见
        self.task_input.show()
        self.task_input.raise_()
        # 连接信号
        self.task_input.returnPressed.connect(self.add_task)

        # 初始化界面
        self.init_ui()

        # 加载示例数据
        self.load_sample_data()

    def init_ui(self):
        """初始化界面"""
        # 设置添加任务按钮样式

        # 加载建议列表
        for suggestion, completed in self.suggestions:
            item = QListWidgetItem()
            self.ui.suggestionListWidget.addItem(item)

            # 创建自定义小部件
            suggestion_widget = QWidget()
            layout = QHBoxLayout(suggestion_widget)
            layout.setContentsMargins(5, 5, 5, 5)

            # 添加复选框
            checkbox = QCheckBox()
            checkbox.setChecked(completed)
            checkbox.setStyleSheet("""
                QCheckBox {
                    spacing: 5px;
                }
                QCheckBox::indicator {
                    width: 16px;
                    height: 16px;
                }
                QCheckBox::indicator:unchecked {
                    image: url(:/images/circle.svg);
                }
                QCheckBox::indicator:checked {
                    image: url(:/images/check.svg);
                }
            """)
            layout.addWidget(checkbox)

            # 添加文本
            text_label = QLabel(suggestion)
            text_label.setStyleSheet("color: #333333; background: transparent;")
            layout.addWidget(text_label)
            layout.addStretch()

            # 设置项目大小
            item.setSizeHint(suggestion_widget.sizeHint())

            # 设置小部件
            self.ui.suggestionListWidget.setItemWidget(item, suggestion_widget)

    def update_date(self):
        """更新日期显示"""
        now = datetime.datetime.now()
        weekday_map = {0: "一", 1: "二", 2: "三", 3: "四", 4: "五", 5: "六", 6: "日"}
        weekday = weekday_map[now.weekday()]
        date_str = f"{now.month}月{now.day}日, 星期{weekday}"
        self.ui.dayLabel.setText(date_str)

    def add_task(self):
        """添加新任务"""
        title = self.task_input.text().strip()
        if title:
            task = TodoTask(title)
            self.tasks.append(task)
            self.add_task_to_list(task)
            # 清空输入框
            self.task_input.clear()
            # 滚动到最新添加的任务
            self.ui.todoListWidget.scrollToItem(self.ui.todoListWidget.item(self.ui.todoListWidget.count() - 1))

    def add_task_to_list(self, task):
        """将任务添加到列表显示"""
        item = QListWidgetItem()
        item.setData(Qt.UserRole, task)

        # 创建自定义小部件
        task_widget = QWidget()
        layout = QHBoxLayout(task_widget)
        layout.setContentsMargins(10, 5, 10, 5)

        # 添加自定义复选框
        checkbox = QCheckBox()
        checkbox.setChecked(task.completed)
        checkbox.setStyleSheet("""
            QCheckBox {
                spacing: 5px;
            }
            QCheckBox::indicator {
                width: 22px;
                height: 22px;
                border-radius: 11px;
                border: 2px solid #ffffff;
                background-color: rgba(255, 255, 255, 0.2);
                transition: all 0.3s;
            }
            QCheckBox::indicator:checked {
                background-color: #2ecc71;
                border: 2px solid #2ecc71;
                image: url(:/images/check.svg);
            }
            QCheckBox::indicator:unchecked:hover {
                border: 2px solid #3498db;
                background-color: rgba(255, 255, 255, 0.3);
            }
        """);
        checkbox.stateChanged.connect(lambda state, t=task: self.toggle_task_state(t, state))
        layout.addWidget(checkbox)

        # 添加任务标题
        title_label = QLabel(task.title)
        title_label.setStyleSheet("""
            color: #ffffff;
            font-size: 15px;
            padding-left: 5px;
            background: transparent;
            font-weight: 400;
        """);
        if task.completed:
            title_label.setStyleSheet(title_label.styleSheet() + "text-decoration: line-through; color: #aaaaaa;")
        layout.addWidget(title_label)
        layout.addStretch()

        # 设置项目大小
        item.setSizeHint(task_widget.sizeHint())

        # 添加到列表
        self.ui.todoListWidget.addItem(item)
        self.ui.todoListWidget.setItemWidget(item, task_widget)

    def toggle_task_state(self, task, state):
        """切换任务完成状态"""
        task.completed = (state == Qt.Checked)

        # 更新任务显示
        for i in range(self.ui.todoListWidget.count()):
            item = self.ui.todoListWidget.item(i)
            item_task = item.data(Qt.UserRole)
            if item_task == task:
                widget = self.ui.todoListWidget.itemWidget(item)
                title_label = widget.findChild(QLabel)
                if task.completed:
                    title_label.setStyleSheet(
                        "color: #aaaaaa; font-size: 14px; padding-left: 5px; text-decoration: line-through; background: transparent;")
                else:
                    title_label.setStyleSheet("color: #ffffff; font-size: 14px; padding-left: 5px;")
                break

    def load_sample_data(self):
        """加载示例数据"""
        # 每个元组包含任务标题和完成状态
        tasks = [
            ("实现todolist界面开发1", False),
            ("实现todolist界面开发2", True),  # 已完成
            ("实现todolist界面开发3", False),
            ("实现todolist界面开发4", True)  # 已完成
        ]
        for title, completed in tasks:
            task = TodoTask(title, completed=completed)
            self.tasks.append(task)
            self.add_task_to_list(task)
